package com.khanacademy;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Category extends ListActivity
{
	private static final String DEBUG_TAG = "KhanAcademy: CATEGORY";
	final Handler handler = new Handler();
	private final int PROGRESS_DIALOG = 1;
	ArrayList<HashMap<String,Object>> videoList = new ArrayList<HashMap<String,Object>>();
	SimpleAdapter simpleAdapter = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // get variables from intent
        final String title = getIntent().getExtras().getString("TITLE");
        final String playlist = getIntent().getExtras().getString("PLAYLIST");
        final int count = getIntent().getExtras().getInt("COUNT");
        
        // set content view
        setContentView(R.layout.main);
        
        // change the title
        TextView titleView = (TextView) findViewById(R.id.title);
        titleView.setText(title);
        
        // display a progress dialog while fetching data
		showDialog(PROGRESS_DIALOG);
    		
        // new thread which downloads the data
    	new Thread()
   		{
    		@Override
    		public void run()
   			{
    			downloadData(playlist, count);
   				handler.post(loadLayout);
   			}
    	}.start();
    }
    
    // progress dialog
    @Override
    protected Dialog onCreateDialog(int id)
    {
    	if (id == PROGRESS_DIALOG)
    	{
    		Log.e(DEBUG_TAG, "Starting Progress Dialog...");
    		ProgressDialog dialog = new ProgressDialog(this);
    		dialog.setMessage("Downloading Videos...");
    		return dialog;
    	}
    	return super.onCreateDialog(id);
    }
    
    // load the layout after the download thread is finished
    final Runnable loadLayout = new Runnable()
    {
    	public void run()
    	{
    		// set the list adapter
        	simpleAdapter = new SimpleAdapter(Category.this, videoList, R.layout.category_list, new String[] {"title"}, new int[] {R.id.title});
            setListAdapter(simpleAdapter);
    		
        	// remove progress dialog
    		dismissDialog(PROGRESS_DIALOG);
    	}
    };
    
    // gets the list item when clicked
    @Override
    public void onListItemClick(ListView l, View v, int position, long id)
    {
    	// get the movie id using the name as a key
    	HashMap<String,Object> item = videoList.get(position);
	    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(item.get("url").toString())));
    }
    
    // download data from the internet
    public void downloadData(String playlist, int count)
    {		
    	try
    	{
    		// need to stick multiple lists together if the count is more than 50
    		for (int c = 1; c < count; c+=50)
    		{		
    			JSONObject jsonObject = JSONParser.getJSONObject("http://gdata.youtube.com/feeds/api/playlists/"+playlist+"?v=2&alt=json&start-index="+c+"&max-results=50");
    			JSONArray entryArray = jsonObject.getJSONObject("feed").getJSONArray("entry");

    			// parse the data
    			for (int i = 0; i < entryArray.length(); i++)
    			{							
    				// create a list item
    				HashMap<String,Object> item = new HashMap<String,Object>();
    			
    				// get this json object from the array
    				JSONObject object = null;
    				try { object = entryArray.getJSONObject(i); }
    				catch (JSONException e) { Log.d(DEBUG_TAG, "JSONException (Object)", e); }
    	        
    				// add the object properties to a hashmap
    				item.put("title", object.getJSONObject("title").get("$t").toString());
    				item.put("url", object.getJSONArray("link").getJSONObject(0).get("href").toString() );
    				videoList.add(item);
    			}
    		}
    	}
    	catch (JSONException e) { Log.e(DEBUG_TAG, "JSONException in downloadData", e); }
    	catch (NullPointerException e) { Log.e(DEBUG_TAG, "NullPointerException in downloadData", e); }
   	}
}